/*
 *  This program is based by daytimtcpsrv.c
 *  It use readline() & writen()
 */
#include	"unp.h"
#include 	<stdio.h>
#include 	<stdlib.h>
#include 	<unistd.h>

#define MAX_SIZE 4096
int
main(int argc, char **argv)
{
	int					listenfd, connfd,filefd, readsize;
	pid_t				childpid;
	socklen_t			clilen;
	struct sockaddr_in	cliaddr, servaddr;
	void				sig_chld(int);
	char				buff[MAX_SIZE], filename[MAX_SIZE];

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(35000);

	Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);

	Signal(SIGCHLD, sig_chld);	/* must call waitpid() */

	for ( ; ; ) {
		clilen = sizeof(cliaddr);
		if ( (connfd = accept(listenfd, (SA *) &cliaddr, &clilen)) < 0) {
			if (errno == EINTR)
				continue;		/* back to for() */
			else
				err_sys("accept error");
		}

		if ( (childpid = Fork()) == 0) {	/* child process */
			Close(listenfd);	/* close listening socket */
			readline(connfd,filename, sizeof(filename));
			printf("%s\n",filename);

			filefd=open(filename, O_WRONLY | O_CREAT, 0644);
			while((readsize=(readline(connfd,buff,sizeof(buff)))) != 0)
				write(filefd,buff,readsize);

			close(filefd);
			exit(0);
		}

		Close(connfd);			/* parent closes connected socket */
	}
}

void sig_chld(int signo)
{
	pid_t	pid;
	int		stat;

	while((pid = waitpid(-1, &stat, WNOHANG))> 0)
	{
		printf("child %d terminated \n",pid);
	}
	return ;
}
